package cn.congzhou.crm.web.controller;

import cn.congzhou.crm.domain.Customer;
import cn.congzhou.crm.domain.Employee;
import cn.congzhou.crm.domain.FormalCustomer;
import cn.congzhou.crm.domain.SystemDictionaryItem;
import cn.congzhou.crm.query.CustomerQueryObject;
import cn.congzhou.crm.service.ICustomerService;
import cn.congzhou.crm.service.IEmployeeService;
import cn.congzhou.crm.service.ISystemDictionaryItemService;
import cn.congzhou.crm.utils.ResultJSON;
import cn.congzhou.crm.utils.UserContext;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Controller
@RequestMapping("/customer")
public class CustomerController {

    private Logger logger = LoggerFactory.getLogger(CustomerController.class);

    @Autowired
    private ICustomerService customerService;

    @Autowired
    private ISystemDictionaryItemService systemDictionaryItemService;

    @Autowired
    private IEmployeeService employeeService;

    @RequestMapping("/list")
    public String list(@ModelAttribute("qo")CustomerQueryObject qo, Model model,Integer cusStatus,Integer source) {
        Employee currentUser = UserContext.getCurrentUser();
//      判断当前登录用户的角色和是否为管理员 TODO 导出数据方法也有这重复的代码，后期看看要不要抽取
        if(SecurityUtils.getSubject().hasRole("CUS_MGR") || currentUser.isAdmin()){
            //设置筛选当前用户的客户，管理员和客户经理显示所有
            qo.setSellerId(null);
        }else {
            qo.setSellerId(currentUser.getId());
        }
        if(cusStatus!=null && cusStatus!=-1){
            qo.setStatus(new Integer[] {cusStatus});
        }
        PageInfo<Customer> pageInfo = customerService.selectByPage(qo);
        //分页查询
        model.addAttribute("ro",pageInfo);
        model.addAttribute("cusStatus",cusStatus);
        //查询所有工作，后面要删掉
        //model.addAttribute("jobs",systemDictionaryItemService.selectAllJobs());
        model.addAttribute("sources",systemDictionaryItemService.selectAllSources());
        // 查询所有交流方式
        model.addAttribute("types",systemDictionaryItemService.selectAllTypes());
        //查询所有课程
        model.addAttribute("curriculums",systemDictionaryItemService.selectAllCurriculum("curriculum"));
        // 当前年份
        Date date = new Date();
        model.addAttribute("currentYear",cn.congzhou.crm.utils.DateUtil.getYeay(date));
        //当前月份
        model.addAttribute("currentMonth",cn.congzhou.crm.utils.DateUtil.getMonth(date));
        //查询所有人员（销售)
        List<Employee> newSellers = employeeService.selectAll();

        Iterator<Employee> iterator = newSellers.iterator();
        //删除自己
        if (iterator.hasNext()){
            if (iterator.next().getId() == currentUser.getId()) {
                iterator.remove();
            }
        }
        //新营销人员
        model.addAttribute("newSellers",newSellers);

        if(source != null && source == 1){
            //访问来源是1表示从添加正式客户，返回添加整数客户查询页面
            return "/formalCustomer/addCustomer";
        }
        return "/customer/list";
    }


    @RequestMapping("/input")
    @RequiresPermissions(value = {"编辑客户信息","customer:input"},logical = Logical.OR)
    public String input(Long id, Model model) {
        if (id != null) {
            model.addAttribute("entity", customerService.selectByPrimaryKey(id));
        }

        return "/customer/input";
    }

//  保存客户信息
    @RequestMapping("/saveOrUpdate")
    @RequiresPermissions(value = {"添加/保存客户信息","customer:saveOrUpdate"},logical = Logical.OR)
    @ResponseBody
    public Object saveOrUpdate(Customer customer) {
        ResultJSON result = new ResultJSON();
        try {
            customerService.saveOrUpdate(customer);

        } catch (Exception e) {
            e.printStackTrace();
            result.mark("保存失败");
        }

        return result;
    }

    @RequestMapping("/updateStatus")
    @RequiresPermissions(value = {"修改客户状态","customer:updateStatus"},logical = Logical.OR)
    @ResponseBody
    public Object changeCustomerStatus(Long id, Integer status) {
        ResultJSON result = new ResultJSON();
        try {
            customerService.changeCustomerStatus(id,status);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark("修改失败");
        }

        return result;
    }

    @RequestMapping("/import.do")
    @RequiresPermissions(value = {"导入客户信息","customer:import"},logical = Logical.OR)
    public String customerImport(MultipartFile xls){
        //解析上传文件的流创建工作簿对象
        HSSFWorkbook book = null;
        try {
            book = new HSSFWorkbook(xls.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(book == null){
            return "redirect://customer/list.do";
        }
        //获取第一张表的名字
        String sheetName = book.getSheetName(0);
        //获取第一张表的内容
        HSSFSheet sheet = book.getSheet(sheetName);
        List<Customer> customers = new ArrayList<>();
        for(int i = 1; i<= sheet.getLastRowNum(); i++){
            Customer customer = new Customer();
            //拼接到备注尾部的信息，用于其他单元格的信息异常无法保存到数据库，将其凭借到备注的尾部
            StringBuilder sb = new StringBuilder();
            //第一行（0）是表头数据，所以从index = 1 开始获取数据 
            HSSFRow row = sheet.getRow(i);
            //日期
            HSSFCell cell01 = row.getCell(0, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
            if (DateUtil.isCellDateFormatted(cell01)){
                Date data = cell01.getDateCellValue();
                customer.setInputTime(data);
            }
            //姓名
            HSSFCell cell02 = row.getCell(1, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
            String name = cell02 == null ? null : cell02.toString();//姓名
            customer.setName(name);
            // 性别
            HSSFCell cell03 = row.getCell(2, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
            String genderStr = cell03 == null ? null :  cell03.toString();
            if("男".equals(genderStr)){
                customer.setGender(1);
            }else if("女".equals(genderStr)){
                customer.setGender(0);
            }
            //年龄
            HSSFCell cell04 = row.getCell(3, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
            String ageStr = cell04 == null ? null : cell04.toString();
            if (ageStr != null && !"".equals(ageStr.trim())){
                Integer age = Integer.valueOf(ageStr.substring(0,ageStr.indexOf(".")));
                customer.setAge(age);
            }
            //电话
            HSSFCell cell05 = row.getCell(4, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
            String telStr = cell05 == null ? null : cell05.toString();
            if(telStr != null){
                try {
                    String tel = new BigDecimal(telStr).toPlainString();
                    customer.setTel(tel);
                }catch (Exception e){
                    customer.setTel(telStr);
                    e.printStackTrace();
                }

            }
            //家庭职业
            HSSFCell cell06 = row.getCell(5, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
            String job = cell06 == null ? null : cell06.toString();
            customer.setJob(job);
            //意向课程
            HSSFCell cell07 = row.getCell(6, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
            String curriculumStr = cell07 == null ? null : cell07.toString();
            SystemDictionaryItem curriculum = systemDictionaryItemService.selectByName(curriculumStr);
            customer.setCurriculum(curriculum);
            if(curriculumStr != null && curriculum == null){
                sb.append(" | 意向课程：").append(curriculumStr);
            }

            //来源
            HSSFCell cell08 = row.getCell(7, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
            String sourcesStr = cell08 == null ? null : cell08.toString();
            SystemDictionaryItem sources = systemDictionaryItemService.selectByName(sourcesStr);
            customer.setSource(sources);
            if(sourcesStr != null && sources == null){
                sb.append(" | 客户来源：").append(sourcesStr);
            }
            //销售人员
            HSSFCell cell09 = row.getCell(8, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
            String saleMan = cell09 == null ? null : cell09.toString();
            Employee sale =  employeeService.selectByName(saleMan);
            customer.setSeller(sale);
            if(saleMan != null && sale == null){
                sb.append(" | 销售员：").append(saleMan);
            }
            //状态
            HSSFCell cell10 = row.getCell(9, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
            String status = cell10 == null ? null : cell10.toString();
            int statusInt = this.statusJudge(status);
            if(4 == statusInt){
                //状态为正式客户，添加到正式库和数据表
              /*  FormalCustomer fc = new FormalCustomer();
                fc.setCustomer(customer);
                fc.setCurriculum(curriculum);*/
            }
            customer.setStatus(statusInt);
            //备注
            HSSFCell cell11 = row.getCell(10, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
            String remark = cell11 == null ? null : cell11.toString();
            String str = sb.toString();
            if(remark == null || "".equals(remark.trim())){
                if(str.length() > 3){
                    customer.setRemark(str.substring(3));
                }
            }else{
                customer.setRemark(remark + str);
            }

            customers.add(customer);
        }
        //以上所有行都解析完毕再插入数据库，避免由于某一行出错导致导入的数据不完整，如果有一条数据报错，则全部数据都不插入
        for (Customer customer : customers) {
            customerService.insertOneCustomer(customer);
        }

        return "redirect:/customer/list.do";
    }

    @RequestMapping("/export")
    @RequiresPermissions(value = {"导出客户信息","customer:export"},logical = Logical.OR)
    public ModelAndView exportExcel(HttpServletResponse response, @ModelAttribute("qo")CustomerQueryObject qo,Integer cusStatus) {
        Employee currentUser = UserContext.getCurrentUser();
//      判断当前登录用户的角色和是否为管理员 TODO 查询数据方法也有这重复的代码，后期看看要不要抽取
        if(SecurityUtils.getSubject().hasRole("CUS_MGR") || currentUser.isAdmin()){
            //设置筛选当前用户的客户，管理员和客户经理显示所有
            qo.setSellerId(null);
        }else {
            qo.setSellerId(currentUser.getId());
        }

        if(cusStatus!=null && cusStatus!=-1){
            qo.setStatus(new Integer[] {cusStatus});
        }

        List<Customer> customers = customerService.exportCustomer(qo);
        //创建工作簿
        HSSFWorkbook book = new HSSFWorkbook();
        //创建纸
        HSSFSheet sheet = book.createSheet("客户信息表");
        //创建第一行表头
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("序号");
        row.createCell(1).setCellValue("日期");
        row.createCell(2).setCellValue("姓名");
        row.createCell(3).setCellValue("性别");
        row.createCell(4).setCellValue("年龄");
        row.createCell(5).setCellValue("电话");
        row.createCell(6).setCellValue("家庭职业");
        row.createCell(7).setCellValue("意向课程");
        row.createCell(8).setCellValue("来源");
        row.createCell(9).setCellValue("营销人员");
        row.createCell(10).setCellValue("状态");
        row.createCell(11).setCellValue("录入人");
        row.createCell(12).setCellValue("备注");
        try{
            //遍历每一条数据写入到Excel表中
            for (int i = 0; i < customers.size(); i++) {
                HSSFRow rowi = sheet.createRow(i + 1);
                Customer customer = customers.get(i);
                rowi.createCell(0).setCellValue(i + 1);
                rowi.createCell(1).setCellValue(customer.getInputTime());
                rowi.createCell(2).setCellValue(customer.getName());
                rowi.createCell(3).setCellValue(customer.getGenderName());
                // Integer包装类自动拆箱有可能会报空指针，所以手动拆箱
                Integer age = customer.getAge();
                String ageStr = "";
                if(age != null){
                   ageStr = age.toString();
                }
                rowi.createCell(4).setCellValue(ageStr);
                rowi.createCell(5).setCellValue(customer.getTel());
                rowi.createCell(6).setCellValue(customer.getJob());
                //意向课程
                HSSFCell cellCurriculum = rowi.createCell(7);
                SystemDictionaryItem curriculum = customer.getCurriculum();
                if (curriculum != null){
                    cellCurriculum.setCellValue(curriculum.getTitle());
                }
                //来源
                HSSFCell cellSource = rowi.createCell(8);
                SystemDictionaryItem source = customer.getSource();
                if(source != null){
                    cellSource.setCellValue(source.getTitle());
                }
                //销售人员
                HSSFCell cellSeller = rowi.createCell(9);
                Employee saleMan = customer.getSeller();
                if(saleMan != null){
                    cellSeller.setCellValue(saleMan.getName());
                }
                // 状态
                rowi.createCell(10).setCellValue(customer.getStatusName());
                //录入人
                HSSFCell cellInputUser = rowi.createCell(11);
                Employee inputUser = customer.getInputUser();
                if(inputUser != null){
                    cellInputUser.setCellValue(inputUser.getName());
                }
                rowi.createCell(12).setCellValue(customer.getRemark());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //指定输出的文件名
        response.setHeader("Content-Disposition","attachment;filename=customer.xls");
        try {
            book.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    private int statusJudge(String status){
        if (status == null){
            return 0;
        }
        int s = 0;
        switch (status){
            case "潜在客户" : s = 0; break;
            case "开发失败" : s = 1; break;
            case "重点关注" : s = 2; break;
            case "客户池" : s = 3; break;
            case "正式客户" : s = 4; break;
            default: s = 0; break;

        }
        return s;
    }

    //==========================添加ligerUI添加的方法============================================//

    @RequestMapping("/toCustomerGrid")
    public String toCustomerGrid(){

        return "/customer/customerMsgGrid";
    }

    //@ResponseBody
    @RequestMapping("/getCustomerData")
    public Object getGridData(CustomerQueryObject qo, HttpServletResponse response){
        PageInfo<Customer> pageInfo = customerService.selectByPage(qo);
        String data = JSON.toJSONStringWithDateFormat(pageInfo, "yyyy-MM-dd");
        //String s = JSON.toJSONString(pageInfo);
        try {
            PrintWriter writer = response.getWriter();
            writer.print(data);
            writer.flush();
        } catch (IOException e) {
            logger.error("IO流出错",e);
        }
        return null;
    }




}
